/*
 *
 *  *    Copyright 2020-2021 luter.me
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */

package com.luter.heimdall.core.utils.crypto;


import com.luter.heimdall.core.utils.StrUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * The type Md 5 util.
 *
 * @author luter
 */
public final class Md5Util {
    /**
     * Instantiates a new Md 5 util.
     */
    private Md5Util() {
    }

    /**
     * Md 5 string.
     *
     * @param plainPassword 明文密码
     * @return the string
     */
    public static String encrypt(String plainPassword) {
        if (StrUtils.isBlank(plainPassword)) {
            throw new IllegalArgumentException("plain password can not be null");
        }
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("md5");
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException(e);
        }
        md.update(plainPassword.getBytes());
        byte[] bytes = md.digest();
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String str = Integer.toHexString(b & 0xFF);
            if (str.length() == 1) {
                sb.append("0");
            }
            sb.append(str);
        }
        return sb.toString();
    }

    /**
     * 是否匹配
     *
     * @param plainPassword  the plain password
     * @param cipherPassword the cipher password
     * @return the boolean
     */
    public static boolean matches(String plainPassword, String cipherPassword) {
        return cipherPassword.equals(encrypt(plainPassword));
    }

    /**
     * The entry point of application.
     *
     * @param args the input arguments
     */
    public static void main(String[] args) {
        System.out.println(Md5Util.encrypt("aaaaaa"));
    }

}
